<template>
  <div class="wrapper">
    <el-card>
      <div class="rowDiv">
        <div class="row-left">
          <div class="row-item">
            <span class="demonstration">时间范围:</span>
            <el-date-picker
              v-model="state.value1"
              @change="chooseTimeRange"
              type="daterange"
              clearable
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
            >
            </el-date-picker>
          </div>
          <div class="row-item">
            仓库:<el-select
              v-model="state.waretype"
              placeholder="选择仓库"
              @change="getOrderlist"
              clearable
            >
              <template v-for="item in state.wareArr" :key="item.warehouse_id">
                <el-option
                  :label="item.name"
                  :value="item.warehouse_id"
                ></el-option>
              </template>
            </el-select>
          </div>
          <div class="row-item">
            状态:<el-select
              v-model="state.bindstore"
              placeholder="选择状态"
              @change="getOrderlist"
              clearable
            >
              <el-option label="待审核" value="10"></el-option>
              <el-option label="已入库" value="20"></el-option>
              <el-option label="已取消" value="99"></el-option>
            </el-select>
          </div>
        </div>
        <el-button size="small" type="primary" @click="new_set_inware()"
          >新建入库</el-button
        >
        <div class="row-right">
          <searchDiv
            :placeholder="state.placeholder"
            @searchClick="searchClick"
          ></searchDiv>
        </div>
      </div>
      <el-table :data="state.tableData" style="width: 100%; margin-top: 20px">
        <el-table-column prop="pre_id" label="编号" width="120">
        </el-table-column>
        <el-table-column label="商品清单" width="300">
          <template v-slot="scope">
            <div
              v-for="item in scope.row.item_names"
              class="textElps"
              :key="item"
            >
              {{ item }}
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="province" label="数量(箱)">
          <template v-slot="scope">
            <div v-for="item in scope.row.item_counts" :key="item">
              {{ item }}
            </div>
          </template>
        </el-table-column>
        <el-table-column label="批次号"> </el-table-column>
        <!-- <el-table-column label="生产日期"> </el-table-column>
        <el-table-column label="有效期"> </el-table-column> -->
        <el-table-column label="采购信息" width="200" align="left">
          <template v-slot="scope">
            <div>发货单:{{ scope.row.delivery_pre_id }}</div>
            <div>供应商:{{ scope.row.supplier_name }}</div>
          </template>
        </el-table-column>
        <el-table-column label="费用">
          <template v-slot="scope">
            <div>入库费:{{ scope.row.inbound_fee }}</div>
            <div>其他费:{{ scope.row.other_fee }}</div>
          </template>
        </el-table-column>
        <el-table-column prop="warehouse_name" label="入库仓库">
        </el-table-column>
        <el-table-column prop="zip" label="状态" width="300">
          <template v-slot="scope">
            <div v-for="item in scope.row.info">
              {{ item }}
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="zip" label="操作人"> </el-table-column>
        <el-table-column prop="note" label="备注">
          <template v-slot="scope">
            {{ scope.row.note
            }}<el-button type="text" @click="show_note(scope)">编辑</el-button>
          </template>
        </el-table-column>
        <el-table-column prop="zip" label="审批意见"> </el-table-column>
        <el-table-column label="操作">
          <template #default="scope">
            <el-button
              v-if="scope.row.can_verify"
              @click.native.prevent="approveBtn(scope, state.tableData)"
              type="text"
              size="small"
            >
              审批
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <Page
        v-if="state.totalPage"
        @changePage="changePage"
        :totalPage="state.totalPage"
      ></Page>
      <!-- 备注 -->
      <el-dialog
        title="备注"
        v-model="state.note_dialogVisible"
        width="20%"
        center
      >
        <span>
          <el-input type="textarea" v-model="state.noteTxt"></el-input>
        </span>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="state.note_dialogVisible = false"
              >取 消</el-button
            >
            <el-button type="primary" @click="sub_note()">提 交</el-button>
          </span>
        </template>
      </el-dialog>
      <!-- 新建发货单 -->
      <el-drawer
        title="新建入库单"
        size="45%"
        :before-close="handleClose"
        v-model="state.new_dialogVisible"
        ref="drawer"
      >
        <div class="conTxt">
          <div class="demo-drawer__content">
            <el-form :label-position="labelPosition" label-width="80px">
              <div class="navTitle">1、选择采购单</div>
              <el-row>
                <el-col :span="8">
                  <el-form-item label="发货单号">
                    <el-select
                      @change="change_send_order"
                      clearable
                      v-model="state.orderObj.send_order"
                      placeholder="请选择发货单号"
                    >
                      <template
                        v-for="item in state.orderObj.orderdataArr"
                        :key="item.id"
                      >
                        <el-option
                          :label="item.name"
                          :value="item.id"
                        ></el-option>
                      </template>
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="入库仓库">
                    <el-select
                      v-model="state.orderObj.for_inware"
                      placeholder="请选择入库仓库"
                    >
                      <template
                        v-for="item in state.orderObj.for_inwareArr"
                        :key="item.warehouse_id"
                      >
                        <el-option
                          :label="item.name"
                          :value="item.warehouse_id"
                        ></el-option>
                      </template>
                    </el-select>
                  </el-form-item>
                </el-col>
              </el-row>
              <div class="navTitle">2、采购清单</div>
              <el-table
                max-height="200"
                :data="state.good_data"
                border
                style="width: 100%"
              >
                <el-table-column prop="goods_name" label="商品名称">
                </el-table-column>
                <el-table-column prop="count" label="总收货(箱)">
                </el-table-column>
                <el-table-column prop="unit_price" label="收货单价">
                </el-table-column>
                <el-table-column prop="residue" label="剩余数量">
                </el-table-column>
                <el-table-column prop="carton" label="入库数(箱)">
                  <template v-slot="scope">
                    <el-input
                      type="number"
                      @change="changeResidue(scope.row)"
                      v-model="scope.row.input_residue"
                      :max="scope.row.input_residue"
                    ></el-input>
                  </template>
                </el-table-column>
                <el-table-column prop="address" label="入库单价(元/箱)">
                  <template v-slot="scope">
                    <el-input
                      type="number"
                      v-model="scope.row.input_unit_price"
                      :max="scope.row.input_unit_price"
                    ></el-input>
                  </template>
                </el-table-column>
                <el-table-column prop="address" label="批次号">
                  <template v-slot="scope">
                    <el-select
                      filterable
                      allow-create
                      default-first-option
                      placeholder="请选择批次号"
                      v-model="scope.row.select_batch"
                    >
                      <el-option
                        v-for="item in scope.row.batch_production"
                        :key="item.id"
                        :label="item.name"
                        :value="item.id"
                      >
                      </el-option>
                    </el-select>
                  </template>
                </el-table-column>
                <el-table-column label="操作">
                  <template #default="scope">
                    <el-button
                      @click.native.prevent="deleteRow(scope.$index)"
                      type="text"
                      size="small"
                    >
                      移除
                    </el-button>
                  </template>
                </el-table-column>
              </el-table>
              <div class="navTitle">3、发货信息</div>
              <el-row>
                <el-col :span="8">
                  <el-form-item label="入库费">
                    <el-input v-model="state.storage_fee"></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="其他费用">
                    <el-input v-model="state.other_fee"></el-input>
                  </el-form-item>
                </el-col>
              </el-row>
              <div class="navTitle">4、备注</div>
              <el-row>
                <el-col :span="10">
                  <el-input
                    type="textarea"
                    v-model="state.storage_note"
                  ></el-input>
                </el-col>
              </el-row>

              <el-row type="flex" justify="center" style="padding: 30px 0">
                <el-col :span="8">
                  收货金额:{{ double.total_price || 0 }}
                </el-col>
                <el-col :span="8">
                  入库金额:{{ double.storage_total || 0 }}
                </el-col>
              </el-row>
              <el-row type="flex" justify="center">
                <el-col :span="4">
                  <el-button @click="state.new_dialogVisible = false"
                    >取消</el-button
                  >
                </el-col>
                <el-col :span="4">
                  <el-button type="primary" @click="submitForm">创建</el-button>
                </el-col>
              </el-row>
            </el-form>
          </div>
        </div>
      </el-drawer>
    </el-card>
  </div>
</template>

<script>
import { ref, computed, onMounted, reactive, getCurrentInstance } from "vue";
import { ElMessageBox, ElNotification } from "element-plus";
import searchDiv from "@/components/Search.vue";
import Page from "@/components/Pagination.vue";
import { parse } from "qs";
export default {
    name:"purchase_inware",
  components: { searchDiv, Page },
  props: {},
  setup() {
    let form = ref("null");
    const double = computed(() => {
      let total_price = 0;
      let storage_total = 0;
      let data = state.good_data;
      // 数量*箱规*价格
      data.forEach((v) => {
        total_price +=
          Number(parseFloat(v.input_residue)) *
          Number(parseFloat(v.carton)) *
          Number(parseFloat(v.input_unit_price));
      });
      storage_total +=
        total_price + Number(state.storage_fee) + Number(state.other_fee);
      return { total_price, storage_total };
    });
    const { ctx } = getCurrentInstance();
    let state = reactive({
      orderObj: {
        send_order: "",
        orderdataArr: [], //发货单数组
        for_inware: "",
        for_inwareArr: [], //入库仓库
      },
      storage_fee: 0,
      other_fee: 0,
      storage_note: "",
      new_dialogVisible: false,
      common_id: "",
      num: "",
      waretype: "",
      value1: "",
      begin_date: "",
      end_date: "",
      keywords: "",
      placeholder: "请输入您要搜索的内容",
      searchval: "",
      page: 1,
      totalPage: "",
      noteTxt: "",
      note_dialogVisible: false,
      order_dialogVisible: false,
      bindstore: "",
      good_data: [
        {
          date: "2016-05-02",
          name: "王小虎",
          address: "上海市普陀区金沙江路 1518 弄",
        },
        {
          date: "2016-05-04",
          name: "王小虎",
          address: "上海市普陀区金沙江路 1517 弄",
        },
        {
          date: "2016-05-01",
          name: "王小虎",
          address: "上海市普陀区金沙江路 1519 弄",
        },
        {
          date: "2016-05-03",
          name: "王小虎",
          address: "上海市普陀区金沙江路 1516 弄",
        },
      ],
      set_form: {
        last_ware: "",
        ware_name: "",
        belong_man: "",
        relate_log: "",
        contact_man: "",
        contact_phone: "",
        ware_address: "",
      },
      rules: {
        last_ware: [
          { required: true, message: "请选择上级仓库", trigger: "change" },
        ],
        ware_name: [
          { required: true, message: "请填写仓库名称", trigger: "blur" },
        ],
        belong_man: [
          { required: true, message: "请选择所属人", trigger: "change" },
        ],
        relate_log: [
          { required: true, message: "请选择物流商", trigger: "change" },
        ],
        contact_man: [
          { required: true, message: "请填写联系人", trigger: "blur" },
        ],
        contact_phone: [
          { required: true, message: "请填写联系电话", trigger: "blur" },
        ],
        ware_address: [
          { required: true, message: "请填写仓库地址", trigger: "blur" },
        ],
      },
      tableData: [],
    });
    // 搜索事件
    function searchClick(searchCon) {
      state.keywords = searchCon;
      getOrderlist();
    }

    // 更改数量
    function changeResidue(item) {
      let current = item.input_residue;
      let origin_num = item.residue;
      if (current < 1) {
        item.input_residue = 1;
      }
      if (current > origin_num) {
        item.input_residue = item.residue;
      }
    }
    // 移除
    function deleteRow(idx) {
      console.log(idx);
      state.good_data.splice(idx, 1);
    }
    // 修改备注
    function show_note(item) {
      state.note_dialogVisible = true;
      state.common_id = item.row.id;
      state.num = item.row.pre_id;
      if (item.row.note) {
        state.noteTxt = item.row.note;
      } else {
        state.noteTxt = "";
      }
    }
    // 提交新建入库单
    function submitForm() {
      let arr = state.good_data;
      let items = [];
      arr.forEach((v) => {
        let obj = {
          id: v.id,
          count: v.input_residue,
          unit_price: v.input_unit_price,
          batch_num:v.select_batch
        };
        items.push(obj);
      });
      let data = {
        receive_id: state.orderObj.send_order || "",
        warehouse_id: state.orderObj.for_inware,
        inbound_fee: state.storage_fee,
        other_fee: state.other_fee,
        note: state.storage_note,
        items: JSON.stringify(items),
        amount: double.value.total_price,
      };
      if (!items.length) return ElNotification.error("请选择商品");
      ctx.$http
        .post("/tanxiaji/supplier/inbound/create/", data)
        .then((res) => {
          if (res.errno == 0) {
            ElNotification.success(res.errmsg);
            state.order_dialogVisible = false;
            getOrderlist();
          } else {
            ElNotification.error(res.errmsg);
          }
        })
        .catch((err) => {
          ElNotification.error(err);
        });
    }
    // 分页
    function changePage(e) {
      state.page = e;
      getOrderlist();
    }
    // 通过审核
    function allow_order() {
      state.order_dialogVisible = false;
    }
    // 获取仓库
    function getWarelist() {
      ctx.$http
        .get("/tanxiaji/erp/depot/ajax/search/", {
          type: 1,
        })
        .then((res) => {
          if (res.errno == 0) {
            state.wareArr = res.data;
            state.orderObj.for_inwareArr = res.data;
          } else {
            ElNotification.error(res.errmsg);
          }
        })
        .catch((err) => {
          ElNotification.error(err);
        });
    }
    // 获取新建入库单的仓库列表
    function get_order_ware() {
      ctx.$http
        .post("/tanxiaji/supplier/receive/short/", {})
        .then((res) => {
          if (res.errno == 0) {
            state.orderObj.orderdataArr = res.data;
          } else {
            ElNotification.error(res.errmsg);
          }
        })
        .catch((err) => {
          ElNotification.error(err);
        });
    }
    // 更改发货单号获取对应的商品
    function change_send_order() {
      let current_order_id = state.orderObj.send_order;
      if (!current_order_id) return;
      let order_items = state.orderObj.orderdataArr.filter(
        (v) => v.id == current_order_id
      )[0].items;
      console.log(order_items);
      order_items.filter((v) => {
        v["input_residue"] = JSON.parse(JSON.stringify(v.residue));
        v["input_unit_price"] = JSON.parse(JSON.stringify(v.unit_price));
        v["batch_production"]=[{id:1,name:'王木生'},{id:2,name:'哈哈哈'}];
        v["select_batch"]="";
      });
      console.log(order_items);
      state.good_data = [...order_items];
    }
    // 关闭弹窗--并清除表单信息
    function new_set_inware() {
      state.new_dialogVisible = true;
      get_order_ware();
      state.orderObj.send_order = "";
      state.orderObj.for_inware = "";
      state.good_data = [];
      state.storage_fee = 0;
      state.other_fee = 0;
      state.storage_note = "";
    }
    // 时间范围取值格式化
    function chooseTimeRange(e) {
      if (e != null) {
        state.begin_date = dayjs(e[0]).format("YYYY-MM-DD");
        state.end_date = dayjs(e[1]).format("YYYY-MM-DD");
      } else {
        state.begin_date = "";
        state.end_date = "";
      }
      getOrderlist();
    }
    function create_ware() {
      form.value.validate((valid) => {
        if (valid) {
          alert("submit!");
          close();
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    }
    onMounted(() => {
      getOrderlist();
      getWarelist();
    });
    // 审批
    function approveBtn(item) {
      ElMessageBox.confirm(
        `是否让编号为${item.row.pre_id}的订单通过审核？`,
        "提示",
        {
          confirmButtonText: "通过审核",
          cancelButtonText: "拒绝通过",
          distinguishCancelAndClose: true,
          type: "warning",
          center: true,
        }
      )
        .then((action) => {
          console.log(action);
          approveAjax(item.row.id, 20);
        })
        .catch((action) => {
          console.log(action);
          if (action == "cancel") {
            approveAjax(item.row.id, 10);
          }
        });
    }
    // 审核的接口
    function approveAjax(id, type) {
      ctx.$http
        .post("/tanxiaji/supplier/inbound/verify/", {
          inbound_id: id,
          verify_type: type,
        })
        .then((res) => {
          if (res.errno == 0) {
            ElNotification.success(res.errmsg);
            getOrderlist();
          } else {
            ElNotification.error(res.errmsg);
          }
        })
        .catch((err) => {
          ElNotification.error(err);
        });
    }
    //获取页面信息
    function getOrderlist() {
      ctx.$http
        .post("/tanxiaji/supplier/inbound/manage/", {
          page: state.page,
          warehouse_id: state.waretype,
          keyword: state.keywords || "",
          status: state.bindstore,
          start_date: state.begin_date,
          end_data: state.end_date,
        })
        .then((res) => {
          if (res.errno == 0) {
            state.tableData = res.data.inbounds;
            state.totalPage = res.data.pages;
          } else {
            ElNotification.error(res.errmsg);
          }
        })
        .catch((err) => {
          ElNotification.error(err);
        });
    }

    // 提交备注修改
    function sub_note() {
      ctx.$http
        .post("/tanxiaji/supplier/erp/oreder/note_info/", {
          num: state.num,
          note: state.noteTxt,
          type_no: 4,
        })
        .then((res) => {
          if (res.errno == 0) {
            ElNotification.success(res.errmsg);
            state.note_dialogVisible = false;
            getOrderlist();
          } else {
            ElNotification.error(res.errmsg);
          }
        })
        .catch((err) => {
          ElNotification.error(err);
        });
    }
    return {
      sub_note,
      approveBtn,
      searchClick,
      form,
      state,
      new_set_inware,
      close,
      create_ware,
      allow_order,
      chooseTimeRange,
      getWarelist,
      getOrderlist,
      changePage,
      show_note,
      change_send_order,
      double,
      changeResidue,
      deleteRow,
      submitForm,
    };
  },
};
</script>
<style lang="scss" scoped>
.wrapper {
  height: 100%;
  .el-card {
    height: 100%;
    .cart-title::before {
      content: " ";
      width: 4px;
      height: 20px;
      background: #1890ff;
      background: #1890ff;
      display: inline-block;
      vertical-align: middle;
      margin-right: 5px;
    }
    .rowDiv {
      display: flex;
      justify-content: space-between;
      align-items: center;
      width: 100%;
      .row-left {
        display: flex;
        width: 70%;
        justify-content: space-between;
        .row-item {
          display: flex;
          align-items: center;
          white-space: nowrap;
        }
      }
      .row-right {
        width: 15%;
        display: flex;
        justify-content: flex-end;
      }
    }
    .el-table /deep/ th {
      background-color: #eaeaea;
      text-align: center;
    }
    .el-table /deep/ td {
      text-align: center;
    }
  }
  .conTxt {
    padding: 0 10px;
  }
}
</style>